package pers.duorhs.common.socket;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Duorhs
 * @date 2022/5/7 14:20
 */
@Component
@Slf4j
public class SocketServerHandler {
    private final SocketIOServer socketIOServer;
    private final ConcurrentHashMap<String, SocketIOClient> map = new ConcurrentHashMap<>();

    @Autowired
    public SocketServerHandler(SocketIOServer socketIOServer) {
        this.socketIOServer = socketIOServer;
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        String user = client.getHandshakeData().getSingleUrlParam("user");
        String[] split = user.split("@");
        if (split.length != 2) {
            return;
        }
        String room = split[1];
        log.info("SERVER: {} 连接上来,加入房间 {}", getUser(client), room);
        client.joinRoom(room);
        client.sendEvent("msg", "hello~");
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        log.info("SERVER: {} 断开连接", getUser(client));
        client.sendEvent("msg", "bye~");
    }

    @OnEvent("msg")
    public void onMsg(SocketIOClient client, AckRequest ackRequest, String msg) {
        System.out.println(getUser(client) + " -> Server :" + msg);
    }

    public String getUser(SocketIOClient client) {
        return client.getHandshakeData().getSingleUrlParam("user").split("@")[0];
    }

    public ArrayList<SocketIOClient> getClients() {
        return new ArrayList<>(socketIOServer.getAllClients());
    }

    public ArrayList<SocketIOClient> getClientsFromRoom(String room) {
        return new ArrayList<>(socketIOServer.getRoomOperations(room).getClients());
    }

    public LinkedHashMap<String, SocketIOClient> getClientsMap() {
        LinkedHashMap<String, SocketIOClient> map = new LinkedHashMap<>();
        socketIOServer.getAllClients().forEach(client -> map.put(getUser(client), client));
        return map;
    }

    public void logout(String name) {
        //getClientsMap().get(name).disconnect();

    }

    public void sendMsg(String clientName, String msg) {
        getClientsMap().get(clientName).sendEvent("msg", msg);
    }

    public void sendMsgToRoom(String name, String msg) {
        socketIOServer.getRoomOperations(name).sendEvent("msg", msg);
    }
}
